package zhtt01.mysql.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import zhtt01.mysql.entity.Organization;
import zhtt01.mysql.service.OrganizationService;
import zhtt01.mysql.utils.RestResponse;

import javax.websocket.server.PathParam;
import java.util.List;

// http://localhost:8080/usermanager-api/organization/1
@RestController
@RequestMapping("/usermanager-api/organization")
public class OrganizationController {

    @Autowired
    private OrganizationService organizationService;

    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    private RestResponse save(@RequestBody Organization organization){
        Long parentId=organization.getParentId();
        if(parentId!=null && parentId>=0){
            Organization parent=organizationService.get(parentId);
            organization.setParent(parent);
        }
        this.organizationService.save(organization);
        return RestResponse.success(organization);
    }

    @RequestMapping(method = RequestMethod.PUT)
    @ResponseBody
    private RestResponse update(@RequestBody Organization organization){
        Long parentId=organization.getParentId();
        if(parentId!=null && parentId>=0){
            Organization parent=organizationService.get(parentId);
            organization.setParent(parent);
        }
        this.organizationService.update(organization);
        return RestResponse.success(organization);
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    @ResponseBody
    private RestResponse get(@PathVariable("id")Long id){
        this.organizationService.get(id);
        return RestResponse.success(null);
    }

    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    private RestResponse getOrgByPId(@RequestParam(name="parentId",required=false)Long parentId,@RequestParam(name="id",required=false)Long id){
        List<Organization> orgList=this.organizationService.getOrgByPId(parentId,id);
        return RestResponse.success(orgList);
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    @ResponseBody
    private RestResponse delete(@PathVariable("id")Long id){
        this.organizationService.delete(id);
        return RestResponse.success(null);
    }

    @RequestMapping(value="/paging",method = RequestMethod.GET)
    @ResponseBody
    private RestResponse paging(@RequestParam(defaultValue = "0") int pageIndex,@RequestParam(defaultValue = "10")int pageSize){
        Page<Organization> orgList= organizationService.paging(pageIndex,pageSize);
        return RestResponse.success(orgList);
    }
}
